<template>
  <div class="app-container" style="margin: 20px;">
    <el-form
      ref="formData"
      :model="formData"
      :rules="rules"
      size="medium"
      label-width="100px"
      @submit.native.prevent
    >
      <el-form-item label="类型" prop="typeId">
        <el-select
          v-model="formData.typeId"
          placeholder="请选择类型"
          clearable
          :style="{ width: '50%' }"
        >
          <el-option
            v-for="(item, index) in typeOptions"
            :key="index"
            :label="item.description"
            :value="item.id"
            :disabled="item.disabled"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="策略" prop="policyId">
        <el-select
          v-model="formData.policyId"
          placeholder="请选择策略"
          clearable
          :style="{ width: '50%' }"
          @change="selectTrigger(formData.policyId)"
        >
          <el-option
            v-for="(item, index) in policyOptions"
            :key="index"
            :label="item.description"
            :value="item.id"
            :disabled="item.disabled"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="stateId">
        <el-select
          v-model="formData.stateId"
          placeholder="请选择状态"
          clearable
          :style="{ width: '50%' }"
        >
          <el-option
            v-for="sta in stateOptions"
            :key="sta.id"
            :label="sta.description"
            :value="sta.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请输入名称"
          clearable
          :style="{ width: '50%' }"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="编号" prop="code">
        <el-input
          v-model="formData.code"
          placeholder="请输入编号"
          clearable
          :style="{ width: '50%' }"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="formData.title"
          placeholder="请输入标题"
          clearable
          :style="{ width: '50%' }"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="上传文件" prop="fileList" :style="{ width: '50%' }">
        <el-upload
          ref="fileList"
          class="upload-file-uploader"
          :action="upload.url"
          :before-upload="handleFileBeforeUpload"
          :file-list="upload.showFileList"
          multiple
          :on-progress="handleFileUploadProgress"
          :on-error="handleUploadError"
          :on-exceed="handleExceed"
          :on-success="handleFileSuccess"
          :headers="upload.headers"
        >
          <el-button size="small" type="primary" icon="el-icon-upload"
            >点击上传</el-button
          >
        </el-upload>
      </el-form-item>
      <el-form-item size="large">
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getOptionsInfo, addDoc, getDoc } from '@/api/pms/doc'
import { getToken } from '@/utils/auth'
import { uploadObj } from '@/settings.js'
export default {
  name: '创建文档',
  components: {},
  props: [],
  data() {
    return {
      formData: {
        fileList: []
      },
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        // url: process.env.VUE_APP_BASE_API + "/common/upload",
        url: uploadObj.upload,
        // 上传的文件列表
        showFileList: [],
        // 大小限制(MB)
        fileSize: 200,
        // 文件类型
        fileType: [
          'doc',
          'xls',
          'ppt',
          'txt',
          'pdf',
          'png',
          'jpg',
          'jpeg',
          'pptx',
          'docx',
          'dwg',
          'gif',
          'stp'
        ]
      },
      params: {},
      rules: {
        typeId: [
          {
            required: true,
            message: '请选择下拉选择',
            trigger: 'change'
          }
        ],
        policyId: [
          {
            required: true,
            message: '请选择下拉选择',
            trigger: 'change'
          }
        ],
        documentName: [
          {
            required: true,
            message: '请输入单行文本',
            trigger: 'blur'
          }
        ],
        code: [
          {
            required: true,
            message: '请输入单行文本',
            trigger: 'blur'
          }
        ],
        title: [
          {
            required: true,
            message: '请输入单行文本',
            trigger: 'blur'
          }
        ],
        stateId: [
          {
            required: true,
            message: '请选择下拉选择',
            trigger: 'change'
          }
        ]
      },
      stateData: [],
      typeOptions: [],
      policyOptions: [],
      stateOptions: [],
      queryParams: { policyid: undefined }
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getInfo()
    let params = this.params.pageParams ? this.params : this.$route.params
    if (params.rowParams) {
      this.params = params
      var url = this.getUrl(params.pageParams.url)
      this.getData(url)
    }
  },
  mounted() {},
  methods: {
    getData(url) {
      this.loading = true
      getDoc(url).then(response => {
        this.formData = response.data
        this.upload.showFileList = response.data.fileList
        this.loading = false
      })
    },
    getInfo() {
      this.loading = true
      getOptionsInfo().then(response => {
        this.typeOptions = response.data.typeOptions
        this.policyOptions = response.data.policyOptions
        this.stateData = response.data.stateOptions
        this.stateOptions = response.data.stateOptions
        this.loading = false
      })
    },
    //类型选择时获取类型状态
    selectTrigger(pid) {
      this.stateOptions = []
      this.stateData.forEach((item, index) => {
        if (item.policyid == pid) {
          this.stateOptions.push(item)
        }
      })
    },
    submitForm() {
      this.$refs['formData'].validate(valid => {
        if (!valid) return
        // TODO 提交表单
        this.typeOptions.forEach((value, i) => {
          //数组循环
          if (value.id == this.formData.typeId) {
            this.formData.systemType = value.description
          }
        })
        this.policyOptions.forEach((value, i) => {
          //数组循环
          if (value.id == this.formData.policyId) {
            this.formData.policy = value.description
          }
        })
        this.stateOptions.forEach((value, i) => {
          //数组循环
          if (value.id == this.formData.stateId) {
            this.formData.state = value.name
          }
        })
        addDoc(this.formData).then(response => {
          if (response.code === 200) {
            this.msgSuccess('创建成功')
            this.$store.dispatch('tagsView/delView', this.$route)
            this.$router.push({ path: '/pms/doc/list' })
          }
        })
      })
    },
    resetForm() {
      this.$refs['formData'].resetFields()
    },
    handleFileBeforeUpload(file) {
      if (this.upload.fileType) {
        let fileExtension = ''
        if (file.name.lastIndexOf('.') > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
        }
        const isTypeOk = this.upload.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true
          if (fileExtension && fileExtension.indexOf(type) > -1) return true
          return false
        })
        if (!isTypeOk) {
          this.$message.error(
            `文件格式不正确, 请上传${this.upload.fileType.join('/')}格式文件!`
          )
          return false
        }
      }
      // 校检文件大小
      if (this.upload.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.upload.fileSize
        if (!isLt) {
          this.$message.error(
            `上传文件大小不能超过 ${this.upload.fileSize} MB!`
          )
          return false
        }
      }
      return true
    },
    handleAdd() {
      console.log('handleAdd')
    },
    handleUpdate(row) {
      console.log('handleUpdate')
    },
    // 文件个数超出
    handleExceed() {
      this.$message.error(`文件个数超出限制`)
    },
    // 上传失败
    handleUploadError(err) {
      this.$message.error('上传失败, 请重试')
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false
      this.formData.fileList.push({
        fileName: file.name,
        path: response.fileName
      })
      this.msgSuccess(response.msg)
    }
  }
}
</script>
<style>
.el-upload__tip {
  line-height: 1.2;
}
</style>
